# coding: utf8

#### yarko ---< F/A (financial aid) forms >----
if ENABLE_FINANCIAL_AID:
    db.define_table( 'fa',
       # Idendtification:
       # - Legal name => fa.person.first_name + fa.person.last_name
       # - Address => fa.person.{address1,address2,city,state,country,zip_code}
       # - email address => fa.person.email
       # Registration:
       # - registration type => fa.percon.attendee_type
       db.Field( 'person', db.auth_user, default=auth.user_id, readable=True, writable=False),
       db.Field('created_on','datetime',default=now, readable=False, writable=False),
       db.Field('modified_on','datetime',default=now, readable=False, writable=False),
       db.Field( 'registration_amount', 'boolean', default=False),
       # Hotel Cost:
       # - number of nights of assitance requested;
       db.Field( 'hotel_nights', 'integer', default=0 ),
       # - total amount requested; label:  "Max 50% of room rate at Crowne Plaza x # nights;" labeled; validated if easy to update room rates.
       db.Field( 'total_lodging_amount', 'double', default='0.00'),
       db.Field( 'roommates', 'string', length=128, default=''),
       # Transportation:
       # - method of transportation / details;
       # db.Field( 'method_of_transportation', 'string', default=''),
       db.Field( 'transportation_details', 'text', default=''),
       # - total amount requested; label: "If you want assistance with your transportation costs, please provide a rough estimate (to nearest US$100)
       #       of how much a round-trip will cost.  Please update your request once final cost is known."
       db.Field( 'transportation_amount', 'double', default='0.00', ),
       # Total:  - read-only field calculated from above 3 sections
       # - registration dollar amount requested; (let applicant specify, as they can ask for just a portion)
       db.Field( 'total_amount_requested', 'double', default='0.0'), # default = ATTENDEE_TYPE_COST[person.attendee_type]),
       #
       # Additional fileds:
       # - minimum at. requested; label "In addition to the desired amount, state the minimum amount of aid you require, below
       #  which you will not be able to attend PyCon.  If we are unable to allocate this minumum amount, we will decline your application
       #  and allocate the funds to others."
       db.Field( 'minimum_amount_requested', 'double', default='0.00', ),
       # - Rational " State why you should come to PyCon, and what you will be doing.
       #    We don't need an essay, but please provide a few sentences of explanation.
       #   Priority will be given to people who make significant contributions to PyCon
       #   and the Python community (e.g. students working on a task, conference speakers,
       #   sprint leaders, developers critical to a sprint, super-enthusiastic sprint newbies
       #   who will give 110% for their project, or people doing public service work with Python)."
       db.Field( 'rationale', 'text', default='' ),
       db.Field('status',default='pending',label=T("Status"), writable=False,readable=False),
       db.Field( 'grant_amount', 'double', default='0.00', writable=False,readable=False),
       migrate=migrate, fake_migrate=fake_migrate)
    
    db.fa.person.requires=IS_IN_DB(db,'auth_user.id','%(last_name)s, %(first_name)s [%(id)s]')
    
    db.fa.registration_amount.comment= T('(cost TBD)')
    db.fa.total_lodging_amount.comment= T('(in ARS pesos)')
    ##db.fa.roommates.comment= XML(str(T('(%s)',A('instructions',_href='#roommates'))))
    db.fa.transportation_details.comment = T('(dates, airports codes, bus stations, etc.)')
    db.fa.transportation_amount.comment= T('(in ARS pesos)')
    db.fa.total_amount_requested.comment= T('(in ARS pesos)')
    db.fa.minimum_amount_requested.comment= T('(in ARS pesos)')
    db.fa.rationale.comment= T('describe why you want to come to PyCon')

    db.fa.status.writable=db.fa.status.readable=auth.has_membership('manager')
    db.fa.status.requires=IS_IN_SET(['pending', 'approved', 'denied'])
    db.fa.grant_amount.writable=db.fa.grant_amount.readable=auth.has_membership('manager')

    #### ---< END: F/A forms >---
    
    #### end fixup
    
    
    body_template="""
    Your Financial Aid Application has been %s.
    Thank you; your updates will be reviewed.
    
    Time:     %s
      Name:        %s %s [#%s]
      Address:     %s 
                   %s, %s %s (%s)
      Email:       %s
    
    
    APPLICATION:
      Registration Type:          %s
      Registration Amount:        $ %4.2f
      
      Number Nights:              %d
      Total Lodging Amount:       $ %4.2f
      Roommates:                  %s
    
     
    TRANSPORTATION:
    %s
    
      Transportation Amount:     $ %4.2f
      
    TOTAL REQUEST:           $ %5.2f
    Minimum Reguest:         $ %5.2f
    
    RATIONALE:
    %s
    
    (This email was automatically generated by PyConAr2012 Registration System)
    """
     
    def email_fa(mode):
        fa=db(db.fa.person==auth.user.id).select()[0]
        person=db(db.auth_user.id==auth.user.id).select()[0]
        body=body_template % (mode, fa.modified_on,
                              person.first_name,person.last_name,person.id,
                              person.address,person.city,person.state,person.zip_code,person.country,
                              person.email,
                              person.attendee_type,
                              fa.registration_amount, fa.hotel_nights, fa.total_lodging_amount, fa.roommates,
                              fa.transportation_details, fa.transportation_amount,
                              fa.total_amount_requested, fa.minimum_amount_requested,
                              fa.rationale
                              )
        if False:  # careful!  I've only just printed this to console, so only use for local testing
            # you could add this:
            # if request.env.http_host == '127.0.0.1:8000'
            # or... output to the screen....
            # response.headers['Content-Type']='text/plain'
            # return str("t2.email(\n"+EMAIL_SENDER+"["+FA_EMAIL_TO+person.email+"]"+"\nsubject="+'PyCon FA Application Updated [#%s]' % fa.id+body+"\n)")
            print "t2.email(\n",EMAIL_SENDER,[FA_EMAIL_TO,person.email],"\nsubject=",'PyCon FA Application Updated [#%s]' % fa.id,body,")"
        else:
            mail.send(to=person.email, cc=FA_EMAIL_TO,
                      subject='Financial Aid Application Updated [#%s]' % fa.id,
                      message=body)
    
    def email_fa_select(query=db.fa.id>0):
        for fa in db(query).select():
            person=db(db.auth_user.id==fa.person).select()[0]
            body=body_template % ("retrieved by a manager", fa.modified_on,
                                  person.first_name,person.last_name,person.id,
                                  person.address1,person.address2,person.city,person.state,person.zip_code,person.country,
                                  person.email,
                                  person.attendee_type,
                                  fa.registration_amount, fa.hotel_nights, fa.total_lodging_amount, fa.roommates,
                                  fa.transportation_details, fa.transportation_amount,
                                  fa.total_amount_requested, fa.minimum_amount_requested,
                                  fa.rationale
                                  )
            if False:  # careful!  I've only just printed this to console, so only use for local testing
                # you could add this:
                # if request.env.http_host == '127.0.0.1:8000'
                # or... output to the screen....
                # response.headers['Content-Type']='text/plain'
                # return str("t2.email(\n"+EMAIL_SENDER+"["+FA_EMAIL_TO+"]"+"\nsubject="+'PyCon FA Application Updated [#%s]' % fa.id+ body+ "\n)")
                print "t2.email(\n",EMAIL_SENDER,[FA_EMAIL_TO],"\nsubject=",'PyCon FA Application Updated [#%s]' % fa.id, body, ")"
            else:
                raise "Saraza"
                mail.send(to=FA_EMAIL_TO,subject='PyCon FA Application Updated [#%s]' % fa.id, message=body)
